$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
var colortypes = ['', 'info', 'success', 'warning', 'danger'];
window.utils = {
    showNotification: function (message, type, from, align) {
        from = from || 'top';
        align = align || 'center';
        type = type || 0;
        $.notify({
            message: message
        }, {
            type: colortypes[type],
            timer: 2000,
            placement: {
                from: from,
                align: align
            }
        });
    },
    showAlert: function (message, option) {
        option = option || {
                sub: '',
                type: 'success'
            };
        swal(message, option.sub, option.type);
    },
    showConfirm: function (message, option, sure, cancel) {
        var default_option = {
            title: message,
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: true,
            closeOnCancel: true
        };
        option = $.extend(default_option, option);
        swal(option, function (isconfirm) {
            if (isconfirm) {
                if (sure) {
                    sure()
                }
            } else {
                if (cancel) {
                    cancel();
                }
            }
        })
    },
    jsonToParams: function (param, key, encode) {
        if (param == null) return '';
        var paramStr = '';
        var t = typeof(param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
        } else {
            for (var i in param) {
                var k = key == null ? i : key + '[' + i + ']';
                paramStr += utils.jsonToParams(param[i], k, encode);
            }
        }
        return paramStr;
    },
    modal: function (title, content, options, callback) {
        if (!options) {
            options = ['取消', '确认'];
        }
        if ($.isFunction(content)) {
            var contentFunc = content;
            content = "数据加载中，请稍后。";
        }
        if ($('#myModal').length == 0) {
            var tpl = '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">' +
                '<div class="modal-dialog  modal-select-promotion" role="document">' +
                '<div class="modal-content">' +
                '<div class="modal-header">' +
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                '<h4 class="modal-title" id="myModalLabel">' + title + '</h4>' +
                '</div>' +
                '<div class="modal-body">' +
                content +
                '</div>' +
                '<div class="modal-footer">';
            if (options.length == 1) {
                tpl += '<button type="button" class="btn btn-success btn-fill">' + options[0] + '</button>';
            } else {
                tpl += '<button type="button" class="btn btn-default btn-simple" data-dismiss="modal">' + options[0] + '</button>' +
                    '<button type="button" class="btn btn-success btn-fill">' + options[1] + '</button>';
            }
            tpl += '</div>' +
                '</div>' +
                '</div>' +
                '</div>';
            $('body').append(tpl);
        } else {
            $('#myModal .modal-title').html(title);
            $('#myModal .modal-body').html(content);
            var footer = '';
            if (options.length == 1) {
                footer += '<button type="button" class="btn btn-success btn-fill">' + options[0] + '</button>';
            } else {
                footer += '<button type="button" class="btn btn-default btn-simple" data-dismiss="modal">' + options[0] + '</button>' +
                    '<button type="button" class="btn btn-success btn-fill">' + options[1] + '</button>';
            }
            $('#myModal .modal-footer').html(footer);
        }
        $('#myModal .btn-default').unbind('click').on('click', function () {
            callback(0);
        })
        $('#myModal .btn-success').unbind('click').on('click', function () {
            callback(1);
        })
        $('#myModal').modal('show');
        if (typeof contentFunc !== 'undefined') {
            contentFunc($('#myModal'));
        }
        return $('#myModal');
    },
    qrcode: function (elm, options) {
        if (elm.qrcode) {
            return;
        }
        if (!options.text) {
            options.text = $(elm).data('text');
        }
        require(['jquery.qrcode'], function () {
            $(elm).qrcode(options);
            elm.qrcode = true;
        });
    }
};
function payModal(page) {
    $('#checkModal').find('button.btn-submit').on('click', function () {
        var startIframe = '<iframe frameborder="0" class="iframebox" width="220" height="220" scrolling="no" src="';
        var endIframe = '"></iframe>';
        var payMethod = $(this).attr('for');
        var htmlContent = '';
        if (payMethod == 'alipay') {
            htmlContent = startIframe + '/payment/alipay/pay?order_id=' + orderId + endIframe;
            $('#checkModal').modal('hide');
            $('#qrcodeModal').find('.modal-title').text('支付宝扫码支付');
            $('#qrcodeModal').find('.modal-body').html(htmlContent);
            $('#qrcodeModal').modal({'backdrop': 'static'});
        } else {
            htmlContent = startIframe + '/payment/wechat/pay?order_id=' + orderId + endIframe;
            $('#checkModal').modal('hide');
            $('#qrcodeModal').find('.modal-title').text('微信扫码支付');
            $('#qrcodeModal').find('.modal-body').html(htmlContent);
            $('#qrcodeModal').modal({'backdrop': 'static'});
        }
    });
    $('#checkModal').find('.close-modal').on('click', function () {
        if (page == 'index') {
            $('#qrcodeModal').find('.modal-body').html('');
            $('#qrcodeModal').modal('hide');
            $('#checkModal').modal('hide');
        } else {
            $.post('/payment/payment/delete', {'order_id': orderId}, function (res) {
                console.log(res);
                $('#qrcodeModal').find('.modal-body').html('');
                $('#qrcodeModal').modal('hide');
                $('#checkModal').modal('hide');
            })
        }
    });
    $('#qrcodeModal').find('.close-modal').on('click', function () {
        $.post('/payment/payment/revoke', {'order_id': orderId}, function (res) {
            utils.showAlert('你可从奖品列表中找到并支付该订单');
            $('input').val('');
            $('#qrcodeModal').find('.modal-body').html('');
            $('#qrcodeModal').modal('hide');
            $('#checkModal').modal('hide');
        })
    });
}
function initValidform(formObj) {
    return formObj.Validform({
        btnSubmit: ".btn-submit",
        postonce: true,
        ajaxPost: true,
        datatype: {
            sponsor: function (gets, obj, curform, regxp) {
                if (gets.length == 0) {
                    return false;
                }
                var ZhCount = 0
                var OtCount = 0
                for (var a = 0; a < gets.length; a++) {
                    var asc = gets.charCodeAt(a)
                    if (asc > 127) {
                        ZhCount++
                    } else {
                        OtCount++
                    }
                }
                if ((ZhCount * 4 + OtCount * 1) > 32) {
                    return '只能输入8个中文字符或32个英文字符';
                } else {
                    return true;
                }
            }
        },
        tiptype: function (msg, o, cssctl) {
            if (!o.obj.is("form")) {//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
                var objtip = o.obj.closest('.form-group').find(".Validform_checktip");
                cssctl(objtip, o.type);
                objtip.text(msg);
                var infoObj = o.obj.closest('.form-group').find(".info");
                if (o.type == 2) {
                    infoObj.fadeOut(200);
                } else {
                    if (infoObj.is(":visible")) {
                        return;
                    }
                    var left = o.obj.position().left + 130,
                        top = o.obj.get(0).top;
                    infoObj.css({
                        // "left": left,
                        "margin-top": top
                    }).show().animate({
                        "margin-top": "10px"
                    }, 200);
                }
            }
        },
        beforeCheck: function (curform) {
            var formobj = curform.serializeObject();
            if(formobj["data[prize][exchange_method]"]=='0'){
                var url = $.trim($('.form-control.exchange_url').val());
                if(url && !/^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test(url)){
                    utils.showNotification('请输入正确的链接（例如：http://www.chinamcloud.com）', 3);
                    return false;
                }
            }else{
                if(formobj["data[prize][type_code]"]=='coupon'){
                    if($('.coupon-card.card .form-group input').length==0){
                        utils.showNotification('至少添加一个自定义字段', 3);
                        return false;
                    }else{
                        $('.coupon-card.card .form-group input').each(function(i,item){
                            if(!$(item).val()){
                                utils.showNotification('自定义字段不能为空', 3);
                                return false;
                            }
                        });
                    }
                }
            }
            //在表单提交执行验证之前执行的函数，curform参数是当前表单对象。
            //这里明确return false的话将不会继续执行验证操作;
        },
        beforeSubmit: function (curform) {
            //在验证成功后，表单提交前执行的函数，curform参数是当前表单对象。
            //这里明确return false的话表单将不会提交;
        },
        callback: function (data) {
            if (data.code == 0) {
                location.href = data.result;
            } else {
                utils.showNotification(data.result, 3);
            }
            //返回数据data是json对象，{"info":"demo info","status":"y"}
            //info: 输出提示信息;
            //status: 返回提交数据的状态,是否提交成功。如可以用"y"表示提交成功，"n"表示提交失败，在ajax_post.php文件返回数据里自定字符，主要用在callback函数里根据该值执行相应的回调操作;
            //你也可以在ajax_post.php文件返回更多信息在这里获取，进行相应操作；
            //ajax遇到服务端错误时也会执行回调，这时的data是{ status:**, statusText:**, readyState:**, responseText:** }；
            //这里执行回调操作;
            //注意：如果不是ajax方式提交表单，传入callback，这时data参数是当前表单对象，回调函数会在表单验证全部通过后执行，然后判断是否提交表单，如果callback里明确return false，则表单不会提交，如果return true或没有return，则会提交表单。
        }
    });
}
function initFileInput(fileInputObj) {
    var crfsToken = fileInputObj.closest('form').find('input[name="_token"]').val();
    var defaultFile = fileInputObj.attr('value');
    var fileObjs = [];
    if (defaultFile) {
        var fileExtension = defaultFile.split('.').pop().toLowerCase();
        if (fileExtension != 'csv') {
            var fileObj = '<img src="' + defaultFile + '" class="kv-preview-data file-preview-image" style="width: 213px;height: 160px">';
        } else {
            var fileObj = '<div class="kv-preview-data file-preview-image" style="width: 213px;height: 160px;overflow: hidden;">' + defaultFile + '</div>';
        }
        fileObjs.push(fileObj);
    }
    fileInputObj.fileinput({
        initialPreview: fileObjs,
        uploadUrl: '/web/prize/upload',
        resizeImage: true,
        maxFileSize: fileInputObj.attr('maxFileSize'),
        maxImageWidth: fileInputObj.attr('maxImageWidth'),
        maxImageHeight: fileInputObj.attr('maxImageHeight'),
        // uploadAsync: true,
        allowedPreviewTypes: ['image'],
        initialPreviewShowDelete: true,
        dropZoneEnabled: false,
        showUploadedThumbs: false,
        showCaption: true,
        showPreview: true,
        uploadExtraData: {"_token": crfsToken},
        allowedFileExtensions: ["csv", "gif", "png", "jpg"],
        // elErrorContainer: "#fileError",
        browseClass: "btn btn-primary",
        browseLabel: "选择文件",
        showUpload: false,
        showCancel: false,
        showRemove: false,
//			uploadClass: "btn btn-info",
//			uploadLabel: "部署",
//			uploadIcon: '<i ></i>',
    }).on('fileselect', function (event, numFiles, label) {
        $(event.target).fileinput('upload');
    }).on('fileuploaded', function (event, data, previewId, index) {
        if (data.response.code == 0) {
            $(event.target).attr('data-code', data.response.result);
            $(event.target).closest('.form-group').find('input[name="' + $(event.target).attr('data-for') + '"]').val(data.response.result);
            // $(event.target).closest('.form-group').find('input[name="' + $(event.target).attr('data-for') + '"]').remove();
            // $(event.target).parent().append('<input type="hidden" value="' + data.response.result + '" data-code="' + data.response.result + '" name="' + $(event.target).attr('data-for') + '">');
        } else {
            showFormError($(event.target), data.response.result);
            $(event.target).fileinput('unlock').fileinput('reset');
        }
    }).on('filecleared', function (event) {
        $(event.target).attr('data-code','');
        $(event.target).parents('.file-input').siblings('input[type=hidden]').val('');
        // $('input[data-code="' + $(event.target).attr('data-code') + '"]').remove();
    }).on('filedeleted', function (event, key) {
        $(event.target).attr('data-code','');
        $(event.target).parents('.file-input').siblings('input[type=hidden]').val('');
        // $('input[data-code="' + $(event.target).attr('data-code') + '"]').remove();
    }).on('filereset', function (event) {
        $(event.target).attr('data-code','');
        $(event.target).parents('.file-input').siblings('input[type=hidden]').val('');
        // $('input[data-code="' + $(event.target).attr('data-code') + '"]').remove();
    }).on('filesuccessremove', function (event, id) {
        $(event.target).attr('data-code','');
        $(event.target).parents('.file-input').siblings('input[type=hidden]').val('');
        // $('input[data-code="' + $(event.target).attr('data-code') + '"]').remove();
    });
}
function showFormError(obj, msg) {
    obj.closest('.form-group').find(".Validform_checktip").addClass('Validform_wrong').text(msg);
    var left = obj.position().left + 130,
        top = obj.get(0).top;
    obj.closest('.form-group').find(".info").css({
        // "left": left,
        "margin-top": top
    }).show().animate({
        "margin-top": "10px"
    }, 200);
}
function paymentPoll() {
    var interval = setInterval(function () {
        $.get('/payment/payment/poll?order_id={{$orderId}}', function (res) {
            if (res != 'null') {
                if (res == 'paid') {
                    var type = 'success';
                } else if (res == 'canceled') {
                    var type = 'warning';
                } else if (res == 'Failed') {
                    var type = 'error';
                }
                utils.showAlert(res, {'sub': '', 'type': type});
                clearInterval(interval);
                window.parent.location.href = '/web/prize/index'
            }
        });
    }, 3 * 1000);
    return interval;
}